package com.oneboot.bbsdemo.controller.common;

import com.oneboot.bbsdemo.utils.Result;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class ExceptionHandler {
    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    public Object handleException(Exception e, HttpServletRequest request) {
        Result result = new Result();
        result.setResultCode(500);

        e.printStackTrace(); // 打印异常的堆栈信息，方便调试。
        result.setMessage("未知异常，请联系管理员");

        // 检查请求是否为ajax，如果是ajax，请求则返回 Result json串,如果不是ajax请求则返回error视图
        String contentHeader = request.getHeader("Content-Type");
        String acceptHeader = request.getHeader("Accept");
        String xRequestedWith = request.getHeader("X-Requested-With");

        if ((contentHeader != null && contentHeader.contains("application/json"))
                || (acceptHeader != null && acceptHeader.contains("application/json"))
                || "XMLHttpRequest".equalsIgnoreCase(xRequestedWith)) {
            // 如果是 AJAX 请求，返回 Result 对象
            return result;
        } else {
            // 如果不是 AJAX 请求，返回 error 视图
            ModelAndView mav = new ModelAndView();
            mav.addObject("message", e.getMessage());
            mav.addObject("url", request.getRequestURL());
            mav.addObject("stackTrace", e.getStackTrace());
            mav.addObject("author", "Odyssey");
            mav.addObject("ltd", "Yething's BBS");
            mav.setViewName("error");
            return mav;
        }
    }
}
